package com.hcg.multidatasourceofanno2.config.datasource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
//    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);
    private static final ThreadLocal<String> datasourceHolder = new ThreadLocal();

    public DynamicDataSource() {
    }

    protected Object determineCurrentLookupKey() {
        return getDatasource();
    }

    public static String getDatasource() {
        if (log.isDebugEnabled()) {
            log.debug("Acquired dataSource {}", datasourceHolder.get());
        }

        return (String)datasourceHolder.get();
    }

    public static void setDatasource(String datasourceName) {
        datasourceHolder.set(datasourceName);
    }

    public static void clearDatasource() {
        datasourceHolder.remove();
    }
}

